package 双向链表;



public class 双向链表 {
	public static void main(String[] args) {
		DuLinkNode node1 = new DuLinkNode(1,"小明");
		DuLinkNode node2 = new DuLinkNode(2,"小红");
		DuLinkNode node3 = new DuLinkNode(3,"小蓝");
		DuLinkNode node4 = new DuLinkNode(4,"小黑");
		
		DuLinkNode node5 = new DuLinkNode(3,"小兰");
		
		DuLinkList list = new DuLinkList();
		
//		list.addDuLinkNode(node1);
//		list.addDuLinkNode(node2);
//		list.addDuLinkNode(node3);
//		list.addDuLinkNode(node4);
//		list.showDuLinkList();
		
		list.addOrderByDuLinkNode(node4);
		list.addOrderByDuLinkNode(node1);
		list.addOrderByDuLinkNode(node3);
		list.addOrderByDuLinkNode(node2);
		list.showDuLinkList();
		
		System.out.println("--------------更新-------------");
		list.updataDuLinkNode(node5);
		list.showDuLinkList();
		
		System.out.println("--------------删除-------------");
		list.deleteDuLinkNode(4);
		list.showDuLinkList();
	}
}

class DuLinkList{
	private DuLinkNode L;

	public DuLinkList() {
		super();
		L = new DuLinkNode();
		L.next = null;
		L.prior = null;
	}
	
	
	public void addDuLinkNode(DuLinkNode newDuLinkNode) {
		
		DuLinkNode p = L;
		
		while(p.next != null) {
			p = p.next;
		}
		
		p.next = newDuLinkNode;
		newDuLinkNode.prior =  p;
	}
	
	public void addOrderByDuLinkNode(DuLinkNode newdDuLinkNode) {
		
		DuLinkNode p = L;
		
		while(p.next != null) {
			if(p.next.no > newdDuLinkNode.no) {
				break;
			}
			p = p.next;
		}
		
		//连接新节点和后一个结点
		newdDuLinkNode.next = p.next;
		//不论是添加还是删除，只要涉及后面一个结点，就判断是否是最后一个结点，否则空指针
		if(p.next != null) {
			p.next.prior = newdDuLinkNode;
		}
		
		
		//连接新节点和前一个结点
		p.next = newdDuLinkNode;
		newdDuLinkNode.prior = p;
	}
	
	public void deleteDuLinkNode(int no) {
		if(L.next == null) {
			System.out.println("链表空！");
		}
		
		DuLinkNode p = L.next;
		
		while(p != null) {
			if(p.no == no) {
				break;
			}
			p = p.next;
		}
		
		p.prior.next = p.next;
		
		//排除删除最后一个情况，最后一个next为空，没有前驱
		if(p.next != null) {
			p.next.prior = p.prior;
		}
	}
	
	public void updataDuLinkNode(DuLinkNode newDuLinkNode) {
		
		DuLinkNode p = L.next;
		
		while(p != null) {
			if(p.no == newDuLinkNode.no) {
				//p = newDuLinkNode;
				p.name = newDuLinkNode.name;
				return;
			}
			p = p.next;
		}
		
		System.out.println("没找到！");
	}
	
	public void showDuLinkList() {
		if(L.next == null) {
			System.out.println("链表空！");
		}
		
		DuLinkNode p = L.next;
		
		while(p != null) {
			System.out.println(p);
			p = p.next;
		}
	}
}


class DuLinkNode{
	public int no;
	public String name;
	
	//直接后继
	public DuLinkNode next;
	//直接前驱
	public DuLinkNode prior;
	
	public DuLinkNode() {
		super();
	}

	public DuLinkNode(int no, String name) {
		super();
		this.no = no;
		this.name = name;
	}

	@Override
	public String toString() {
		return "DuLinkNode [no=" + no + ", name=" + name + "]";
	}
}